package cn.itzzx.lagou.config;

import cn.itzzx.lagou.datasource.DataSourceHandler;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * TODO
 *
 * @author Martin
 * @since 1.0
 */
@Configuration
public class WebConfiguration {

    @Value("${zkAddr}")
    private String zkAddr;
    @Value("${dataSourcePath}")
    private String dataSourcePath;


    @Bean
    public CuratorFramework curatorFramework() throws Exception {
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
                .connectString(zkAddr)
                .connectionTimeoutMs(5000)  //连接超时时间
                .sessionTimeoutMs(5000)     //会话超时时间
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .build();
        curatorFramework.start();

        // 设置监听路径
        NodeCache nodeCache = new NodeCache(curatorFramework, dataSourcePath);
        // 设置监听方法
        nodeCache.getListenable().addListener(() -> {
            String data = new String(curatorFramework.getData().forPath(dataSourcePath));
            System.out.println("监听到数据库配置信息更新 " + data);
            String[] datasource = data.split(",");
            DataSourceHandler.setConnentInfo(datasource[0], datasource[1], datasource[2]);
        });
        nodeCache.start();
        return curatorFramework;
    }
}
